//
//  CountrysViewController.m
//  TravelYo
//
//  Created by lanou3g on 15/10/30.
//  Copyright © 2015年 TravelYo. All rights reserved.
//

#import "CountrysViewController.h"
#import "MapViewController.h"

@interface CountrysViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *sectionsArray;

@property (nonatomic, strong) NSMutableDictionary *dataDic;

@property (nonatomic, strong) NSMutableArray *citys;


@end

@implementation CountrysViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self addSubViews];
    [self.tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:@"tableViewCell"];
    [self setUpdata];
    
    // Do any additional setup after loading the view.
}


// 添加子视图
- (void)addSubViews
{
    
 
    DingWeiView *view = [[DingWeiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    [view.dingweiBT addTarget:self action:@selector(actionDingWei:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:view];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, kScreenWidth, kScreenHeight - 64) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)actionRightButton
{
    // NSLog(@"123456");
}

- (NSMutableArray *)citys
{
    if (!_citys) {
        _citys = [NSMutableArray array];
    }
    return _citys;
}

- (NSMutableArray *)sectionsArray
{
    if (!_sectionsArray) {
        _sectionsArray = [NSMutableArray array];
    }
    return _sectionsArray;
}

- (NSMutableDictionary *)dataDic
{
    if (!_dataDic) {
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}


#pragma mark ----- tableView 代理方法


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 300;
    }
    return 50;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.sectionsArray;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    NSMutableArray *array = self.dataDic[self.sectionsArray[section]];
    return array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionsArray.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.sectionsArray[section];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"forIndexPath:indexPath];
        NSString *key = self.sectionsArray[indexPath.section];
        NSArray *dataArray =  self.dataDic[key];
        NSInteger i = 0;
        cell.baliBT.tag = 11;
        cell.taibeiBT.tag = 12;
        cell.qingmaiBT.tag = 13;
        cell.jingduBT.tag = 14;
        cell.luomaBT.tag = 15;
        cell.dabanBT.tag = 16;
        cell.shouerBT.tag = 17;
        cell.manguBT.tag = 18;
        cell.dongjingBT.tag = 19;
        for (id view in cell.contentView.subviews) {
            if ([[view class] isSubclassOfClass:[UIImageView class]]) {
                AllCountryModel *model = dataArray[i];
                [view sd_setImageWithURL:[NSURL URLWithString:model.photo]];
            
                i++;
            }
            
            if ([[view class] isSubclassOfClass:[UIButton class]]) {
            
                [view addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)];
            }
            
        }
        return cell;
    }
    
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    NSString *key = self.sectionsArray[indexPath.section];
    NSArray *dataArray =  self.dataDic[key];
    AllCountryModel *model = dataArray[indexPath.row];
    cell.textLabel.text = model.cnname;
    cell.detailTextLabel.text = model.enname;
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section > 0) {
       MapViewController *mapVC = [[MapViewController alloc] init];
        NSString *key = self.sectionsArray[indexPath.section];
        NSArray *array = self.dataDic[key];
        AllCountryModel *model = array[indexPath.row];
        mapVC.lat = model.lat;
        mapVC.lng = model.lng;
        [self.navigationController pushViewController:mapVC animated:YES];
    }
    
}

- (void)actionButton:(UIButton *)button
{
    NSLog(@"%ld", button.tag);
    NSString *key = self.sectionsArray[0];
    NSArray *dataArray =  self.dataDic[key];
    AllCountryModel *model = dataArray[button.tag - 11];
    MapViewController *mapVC = [[MapViewController alloc] init];
    mapVC.lat = model.lat;
    mapVC.lng = model.lng;
    [self.navigationController pushViewController:mapVC animated:YES];
    
}


#pragma mark ---- 定位
- (void)actionDingWei:(UIButton *)button
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"不支持中国定位" preferredStyle:(UIAlertControllerStyleAlert)];
    [self presentViewController:alert animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
        [self dismissViewControllerAnimated:YES completion:nil];
    });
}

- (void)actionCancel:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}


//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    NSLog(@"111");
//}

// 解析数据
- (void)setUpdata
{
    [[TYDataManager shareManager] requestDataWithUrl:kLvTuAPI block:^ (NSData *data){
        
        NSMutableDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = diction[@"data"];
        NSMutableArray *array = [NSMutableArray array];
        
        for (int i = 0; i < 9; i++) {
            NSDictionary *dic = arr[i];
            AllCountryModel *model = [[AllCountryModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.citys addObject:model];
        }
        
        [self.dataDic setObject:self.citys forKey:@"热"];
        for (NSDictionary *dic in arr) {
            
           NSArray *allKey = [self.dataDic allKeys];
            AllCountryModel *model = [[AllCountryModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            NSString *str = [[model.pinyin substringToIndex:1] uppercaseString];
            if (![array containsObject:str]) {
                [array addObject:str];
            }
            
            if (![allKey containsObject:str]) {
                NSMutableArray *dataArray = [NSMutableArray array];
                [dataArray addObject:model];
                [self.dataDic setObject:dataArray forKey:str];
            } else {
                NSMutableArray *dataArray = self.dataDic[str];
                [dataArray addObject:model];
            }
        }
        [array sortUsingSelector:@selector(compare:)];
        [array insertObject:@"热" atIndex:0];
        self.sectionsArray = array;
        [self.tableView reloadData];
      
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
